package main

import "fmt"

func spiralOrder(matrix [][]int) []int {
	m := len(matrix)
	n := len(matrix[0])
	result := make([]int, 0, m*n)
	i := -1
	j := -1
	for { // 一次循环转一圈
		// 向右
		i++
		j++
		for ; j < n; j++ {
			// 利用 -100 <= matrix[i][j] <= 100 的特性判断是否被访问过
			if matrix[i][j] < -100 {
				break
			}
			result = append(result, matrix[i][j])
			matrix[i][j] -= 200
		}
		// 向下
		i++ // m[i][j] 已经访问过了
		j--
		for ; i < m; i++ {
			if matrix[i][j] < -100 {
				break
			}
			result = append(result, matrix[i][j])
			matrix[i][j] -= 200
		}
		// 向左
		i--
		j--
		for ; j >= 0; j-- {
			if matrix[i][j] < -100 {
				break
			}
			result = append(result, matrix[i][j])
			matrix[i][j] -= 200
		}
		// 向上
		j++
		i--
		for ; i >= 0; i-- {
			if matrix[i][j] < -100 {
				break
			}
			result = append(result, matrix[i][j])
			matrix[i][j] -= 200
		}
		if len(result) == m*n {
			break
		}
	}
	return result
}

func main() {
	ret := spiralOrder([][]int{
		{1, 2, 3},
		{4, 5, 6},
		{7, 8, 9},
	})
	fmt.Printf("%v\n", ret)
	ret = spiralOrder([][]int{
		{1, 2, 3, 4},
		{5, 6, 7, 8},
		{9, 10, 11, 12},
	})
	fmt.Printf("%v\n", ret)
}
